package huizhi.xmltest;

//import org.jdom2.Document;
//import org.jdom2.Element;
//import org.jdom2.input.SAXBuilder;
//import org.w3c.dom.*;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.*;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

public class XmlExerciseDemo1 {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        //dom解析
//        domTest();
//        domTest2();
//        saxTest();
//        jdomTest();
        dom4jTest();
    }

    private static void dom4jTest() {
        try {
            // Load the XML file using dom4j
            File xmlFile = new File("D:\\CodeAll\\code\\Exercies\\\\src\\huizhi\\xmltest\\StudentTable.xml");
            SAXReader reader = new SAXReader();
            Document document = reader.read(xmlFile);

            // Get the root element
            Element rootElement = document.getRootElement();

            // Get all student elements
            List<Element> studentList = rootElement.elements("student");

            // Iterate through each student
            for (Element studentElement : studentList) {
                // Extract data from student element
                String name = studentElement.elementText("name");
                String age = studentElement.elementText("age");
                String grade = studentElement.elementText("grade");
                String subject = studentElement.elementText("subject");

                // Print student information
                System.out.println("Name: " + name);
                System.out.println("Age: " + age);
                System.out.println("Grade: " + grade);
                System.out.println("Subject: " + subject);
                System.out.println("------------------------");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

//    private static void jdomTest() {
//        try {
//            // Load the XML file
//            File xmlFile = new File("D:\\CodeAll\\code\\Exercies\\src\\huizhi\\xmltest\\StudentTable.xml");
//
//            // Create a JDOM document
//            SAXBuilder saxBuilder = new SAXBuilder();
//            Document document =  saxBuilder.build(xmlFile);
//
//            // Get the root element
//            Element rootElement = document.getRootElement();
//
//            // Get all student elements
//            List<Element> studentList = rootElement.getChildren("student");
//
//            for (Element studentElement : studentList) {
//                // Extract data from student element
//                String name = studentElement.getChildText("name");
//                String age = studentElement.getChildText("age");
//                String grade = studentElement.getChildText("grade");
//                String subject = studentElement.getChildText("subject");
//
//                // Print extracted information
//                System.out.println("Name: " + name);
//                System.out.println("Age: " + age);
//                System.out.println("Grade: " + grade);
//                System.out.println("Subject: " + subject);
//                System.out.println("------------------------");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }

    private static void saxTest() {
        try {
            // Create a SAXParserFactory
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            // Create a handler for SAX events
            DefaultHandler handler = new DefaultHandler() {
                boolean inStudent = false;
                boolean inName = false;
                boolean inAge = false;
                boolean inGrade = false;
                boolean inSubject = false;

                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                    if (qName.equalsIgnoreCase("student")) {
                        inStudent = true;
                    } else if (qName.equalsIgnoreCase("name")) {
                        inName = true;
                    } else if (qName.equalsIgnoreCase("age")) {
                        inAge = true;
                    } else if (qName.equalsIgnoreCase("grade")) {
                        inGrade = true;
                    } else if (qName.equalsIgnoreCase("subject")) {
                        inSubject = true;
                    }
                }

                @Override
                public void characters(char[] ch, int start, int length) throws SAXException {
                    if (inName) {
                        System.out.println("Name: " + new String(ch, start, length));
                    } else if (inAge) {
                        System.out.println("Age: " + new String(ch, start, length));
                    } else if (inGrade) {
                        System.out.println("Grade: " + new String(ch, start, length));
                    } else if (inSubject) {
                        System.out.println("Subject: " + new String(ch, start, length));
                    }
                }

                @Override
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    if (qName.equalsIgnoreCase("student")) {
                        inStudent = false;
                    } else if (qName.equalsIgnoreCase("name")) {
                        inName = false;
                    } else if (qName.equalsIgnoreCase("age")) {
                        inAge = false;
                    } else if (qName.equalsIgnoreCase("grade")) {
                        inGrade = false;
                    } else if (qName.equalsIgnoreCase("subject")) {
                        inSubject = false;
                    }
                }
            };

            // Parse the XML file using the handler
            saxParser.parse(new File("D:\\CodeAll\\code\\Exercies\\src\\huizhi\\xmltest\\StudentTable.xml"), handler);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    private static void domTest2() throws ParserConfigurationException, IOException, SAXException {
//        try {
//            // Load the XML file
//            File xmlFile = new File("D:\\CodeAll\\code\\Exercies\\src\\huizhi\\xmltest\\StudentTable.xml");
//            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
//            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//            org.w3c.dom.Document document = dBuilder.parse(xmlFile);
//            document.getDocumentElement().normalize();
//
//            // Get the root element
//            org.w3c.dom.Element rootElement = document.getDocumentElement();
//
//            // Get all student nodes
//            NodeList studentList = rootElement.getElementsByTagName("student");
//
//            for (int i = 0; i < studentList.getLength(); i++) {
//                Node studentNode = studentList.item(i);
//                if (studentNode.getNodeType() == Node.ELEMENT_NODE) {
//                    Element studentElement = (Element) studentNode;
//
//                    // Extract data from student node
//                    String name = studentElement.getElementsByTagName("name").item(0).getTextContent();
//                    String age = studentElement.getElementsByTagName("age").item(0).getTextContent();
//                    String grade = studentElement.getElementsByTagName("grade").item(0).getTextContent();
//                    String subject = studentElement.getElementsByTagName("subject").item(0).getTextContent();
//
//                    // Print extracted information
//                    System.out.println("Name: " + name);
//                    System.out.println("Age: " + age);
//                    System.out.println("Grade: " + grade);
//                    System.out.println("Subject: " + subject);
//                    System.out.println("------------------------");
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    private static void domTest() throws ParserConfigurationException, IOException, SAXException {
        //创建DocumentBuilderFactory对象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //通过DocumentBuilderFactory的对象创造DocumentBuilder对象
        DocumentBuilder db = dbf.newDocumentBuilder();
        //通过DocumentBuilder的对象parser方法加载xml文件到当前项目下
        org.w3c.dom.Document document = db.parse("D:\\CodeAll\\code\\Exercies\\src\\huizhi\\xmltest\\StudentTable.xml");
        //获取所有节点的集合
        NodeList person = document.getElementsByTagName("person");
        System.out.println("一共共有"+person.getLength()+"个节点");
        //遍历每一个data节点
        for (int i = 0; i < person.getLength(); i++) {
            Node book = person.item(i);
            NamedNodeMap attrs = book.getAttributes();
            System.out.println(attrs.getLength());
            for (int j = 0; j < attrs.getLength(); j++) {
                Node attr = attrs.item(j);
                System.out.println("属性名为"+attr.getNodeName());
                System.out.println("属性值为"+attr.getNodeValue());
            }
            //解析子节点
            NodeList childNodes = document.getChildNodes();
            System.out.println(childNodes.getLength());
            for (int k = 0; k < childNodes.getLength() ; k++) {
                Node childNode = childNodes.item(k);
                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println("子节点名称为：" + childNode.getNodeName());
                    // 如果需要，可以继续解析这个子节点的属性
                    NamedNodeMap childAttrs = childNode.getAttributes();
                    for (int l = 0; l < childAttrs.getLength(); l++) {
                        Node childAttr = childAttrs.item(l);
                        System.out.println("子节点属性名为：" + childAttr.getNodeName());
                        System.out.println("子节点属性值为：" + childAttr.getNodeValue());
                    }
                }
            }
        }


    }
}
